#ifndef __MQ_THREADPOOL_
#define __MQ_THREADPOOL_

#include <iostream>
#include <functional>
#include <memory>
#include <thread>
#include <future>
#include <mutex>
#include <condition_variable>
#include <vector>

namespace MQ
{
    class ThreadPool
    {
        using Functor = std::function<void(void)>;

    public:
        using ptr = std::shared_ptr<ThreadPool>;
        ThreadPool(int thread_count = 1)
            : _stop(false)
        {
            for (int i = 0; i < thread_count; ++i)
            {
                _threadpool.emplace_back(&ThreadPool::entry, this);
            }
        }

        ~ThreadPool()
        {
            stop();
        }

        void stop()
        {
            // if (_stop == true)
            //     return;
            _stop = true;
            _cv.notify_all();
            for (auto &thread : _threadpool) // &thread
            {
                thread.join();
            }
        }

        template <typename F, typename... Args>
        auto push(F &&func, Args &&...args) -> std::future<decltype(func(args...))>
        {
            // 传入的函数封装为一个可调用对象
            using return_type = decltype(func(args...));
            auto tmp_func = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
            auto task = std::make_shared<std::packaged_task<return_type()>>(tmp_func);
            std::future<return_type> fut = task->get_future();
            // 构建一个lambda表达式，捕获任务对象
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _taskpool.push_back([task]()
                                    { (*task)(); });
                _cv.notify_one();
                // 将匿名对象抛入到任务池中
            }
            return fut;
        }

    private:
        // 线程入口函数
        void entry()
        {
            while (!_stop)
            {
                std::vector<Functor> tmp_taskpool;
                {
                    // mutex
                    std::unique_lock<std::mutex> lock(_mutex);

                    // 任务池不为空 或 _stop
                    _cv.wait(lock, [this]()
                             { return _stop || !_taskpool.empty(); });

                    if (_stop && _taskpool.empty())
                        return;

                    tmp_taskpool.swap(_taskpool);
                }
                for (auto &task : tmp_taskpool)
                {
                    task();
                }
            }
        }

    private:
        std::atomic<bool> _stop;
        std::vector<Functor> _taskpool;       // task pool
        std::vector<std::thread> _threadpool; // thread pool
        std::condition_variable _cv;
        std::mutex _mutex;
    };
}

#endif